{{ template "layout/header" .}}
{{/*<script src="//cdn.ckeditor.com/4.12.1/full/ckeditor.js"></script>*/}}
<style>
    .tagactive {
        color: #9B703F;
        font-weight: bold;
        background-color: papayawhip;
    }
</style>
<link rel="stylesheet" href="/static/css/ckstyles.css">
<script src="/static/js/ck5b/ckeditor.js"></script>
<main id="body">
    <div class="container">
        <div class="row">
            <div class="col-lg-10 mx-auto">
                <div class="card">
                    <div class="card-header">
                        发表主题
                    </div>
                    <div class="card-body">
                        <form action="/api/v1/thread" method="post" id="threadform">
                            <div class="form-group">
                                <select id="select_forum_id" class="custom-select mr-1 w-auto" name="forum_id">
                                    {{range .forums}}
                                        <option value="{{.ID}}">{{.Name}}</option>
                                    {{end}}
                                </select>
                            </div>


                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="标题" name="subject" value=""
                                       id="subject2">
                            </div>

                            <div style="padding-bottom: 0.8rem;" class="tab" id="taglist">
                                <div>
                                    <table>
                                        <tbody>
                                        <tr>
                                            <td valign="top" style="white-space: nowrap"><span class="grey">电影时间：</span>
                                            </td>
                                            <td>
                                                <a href="forum-index-fid-951-typeid1-0-typeid2-0-typeid3-0-typeid4-1238897.htm"
                                                   rel="nofollow">2019</a>
                                                <a href="forum-index-fid-951-typeid1-0-typeid2-0-typeid3-0-typeid4-1238897.htm"
                                                   rel="nofollow">2019</a>
                                            </td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="edui-container" style="width: 100%; z-index: 999;">
                                    <div class="edui-editor-body message">
                                        <textarea class="form-control" placeholder="内容" name="message" id="message"
                                                  style="height: 300px; display: none;"></textarea>
                                    </div>
                                </div>
                            </div>
                            {{ template "layout/captcha" .}}

                            <div class="d-flex justify-content-between">
                                <div class="attachlist_parent">
                                    <a class="small text-left" href="javascript:void(0)">
                                        <label class="addattach" id="addattach">
                                            <i class="icon-folder-open-o"></i>
                                            添加附件
                                            <input type="file" id="add_attach" multiple="multiple" class="invisible">
                                        </label>
                                    </a>

                                </div>
                                <div class="text-right">
                                    <button type="button" class="btn btn-primary" id="threadsubmit"
                                            data-loading-text="正在提交..."> 提交
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <a role="button" class="btn btn-secondary btn-block xn-back col-lg-6 mx-auto mb-3"
                   href="javascript:history.back();">返回</a>
            </div>
        </div>
    </div>
</main>
<script>
    //判断是否已登录  如未登录 跳转到登录页
    if (!{{.islogin }}) {
        location.href = "/login.html"
    }

    /*CKEDITOR.replace('message', {
        language: 'zh-cn',
        disallowedContent: '<script >',
        // toolbar: [['Smiley']],
        // toolbarCanCollapse: true,
        toolbarStartupExpanded: false,
        toolbar: [
            {name: 'document', items: ['Source', '-', 'Preview']},
            {name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', '-', 'Undo', 'Redo']},
            {name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'RemoveFormat']},
            {name: 'colors', items: ['TextColor']},
            {
                name: 'paragraph',
                items: ['NumberedList', 'BulletedList', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-']
            },
            {name: 'links', items: ['Link', 'Unlink']},
            {name: 'insert', items: ['Image', 'Smiley', 'Table', 'HorizontalRule', 'SpecialChar']},
            '/',
            {name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize']},
            {name: 'tools', items: ['Maximize', 'ShowBlocks']},
        ],
        height: '25rem',
        resize_minHeight: '5rem',
        image_previewText: " ",
        upload_hidden: false,
        removeDialogTabs: 'image:advanced;image:Link',
        filebrowserImageUploadUrl: "/api/v1/image/upload",
        filebrowserUploadUrl: "/api/v1/image/upload",
        //enterMode:CKEDITOR.ENTER_BR, //屏蔽换行符<br>
        //shiftEnterMode:CKEDITOR.ENTER_P, //屏蔽段落<p>
        extraPlugins: 'uploadimage',
        // extraPlugins:['codesnippet','uploadimage'],
        codeSnippet_theme: 'zenburn'
    });*/

    var myeditor = null;
    ClassicEditor.create(document.querySelector('#message'), {

        toolbar: {
            items: [
                'exportPdf',
                'heading',
                '|',
                'bold',
                'italic',
                'underline',
                'fontColor',
                'fontSize',
                'fontFamily',
                'highlight',
                'alignment',
                'link',
                'bulletedList',
                'numberedList',
                '|',
                'indent',
                'outdent',
                '|',
                'imageUpload',
                'blockQuote',
                'insertTable',
                'mediaEmbed',
                'undo',
                'redo',
                '|',
                'codeBlock',
                'code',
                'horizontalLine'
            ]
        },
        language: 'zh-cn',
        image: {
            toolbar: [
                'imageTextAlternative',
                'imageStyle:full',
                'imageStyle:side'
            ]
        },
        table: {
            contentToolbar: [
                'tableColumn',
                'tableRow',
                'mergeTableCells'
            ]
        },
        licenseKey: '',
        ckfinder:{
            'uploadUrl':'/api/v1/image/upload',
        },

    })
        .then(editor => {
            myeditor = editor
        })
        .catch(error => {
            console.error('Oops, something went wrong!');
            console.error(error);
        });

    var qrform = $("#threadform")
    var jsubmit = $('#threadsubmit');
    var attachUploader = $("#add_attach");
    var jattachparent = $('.attachlist_parent');
    var maxSize = 1 * 1024 * 1024

    qrform.on("keydown", function () {
        if (event.keyCode == 13) {
            return false;
        }
    })

    jsubmit.on('click', function () {
        var tags = []
        // 获取标签
        $("#taglist").find(".tagactive").each(function () {
            tags.push($(this).attr("tagid"))
        })
        // console.log(tags)
        tags = tags.toString()
        /*console.log(tags)
        return*/

        var attachfiles = ""
        if (jattachparent.find('.attachlist').length) {
            console.log($('.attachlist').find("li").length, $('.attachlist').find("li"))
            var attachfiles = ""
            $('.attachlist').find("a[class='attachfile']").each(function () {
                attachfiles += "," + $(this).attr("href") + "|"
                attachfiles += $(this).attr("orgfilename")
            })
            attachfiles = trimChar(attachfiles, ',', 'left')
            console.log(attachfiles)
        }

        // 验证验证码
        var captcha = getCaptcha()
        var captchaKey = getCaptchaKey()
        captchaPass = virefyCaptcha(captcha, captchaKey)
        if (captcha.length == 0) {
            $.alert("验证码不能为空")
            return
        } else {
            if (captchaPass != 200) {
                $.alert("验证码错误")
                refreshCaptcha()
                return
            }
        }

        var cktitle = $("#subject2").val()
        if (cktitle.length <= 5) {
            $.alert("标题不能为空切不能小于5个字")
            return
        }

        var ckmessage = myeditor.getData();
        console.log(ckmessage);
        // return;
        if (ckmessage.length < 30) {
            $.alert("内容不能为空切不能小于30字")
            return
        }

        // 进行文本是否包内含违法内容的验证
        /*
        * 获取标题和帖子内容：并且合并成一个内容发送验证
        * */
        var content = cktitle + ckmessage
        var sensitive = false
        $.ajax({
            type: 'POST',
            url: "/api/v1/content_check",
            async:false,
            data: {"content":content},
            success: function(r){
                console.log(r)
                if (r.code != 201) {
                    $.alert(r.message)
                    refreshCaptcha()
                    sensitive = true
                    return
                }
            }
        })

        if (sensitive) {
            return
        }

        // return

        qrform.reset();
        jsubmit.button('loading');
        var postdata = qrform.serializeObject();
        postdata.message = ckmessage
        postdata.attachfiles = attachfiles
        postdata.tagthreads = tags
        console.log(postdata)
        // return;

        $.xpost(qrform.attr('action'), postdata, function (code, message) {
            console.log(code, ":", message)
            // return;
            if (code == 200) {
                afterAddNewThread()
                $.alert(message);
                setTimeout(function () {
                    href = "/forum/" + $("#select_forum_id").val() + "/list.html"
                    location.href = href
                }, 2000)
            } else {
                $.alert(message)
                return
            }
        });

        return false;
    });

    function afterAddNewThread() {
        var jsubmit = $('#postsubmit')
        jsubmit.button('reset');
    }

    function trimChar(str, char, type) {
        if (char) {
            if (type == 'left') {
                return str.replace(new RegExp('^\\' + char + '+', 'g'), '');
            } else if (type == 'right') {
                return str.replace(new RegExp('\\' + char + '+$', 'g'), '');
            }
            return str.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
        }
        return str.replace(/^\s+|\s+$/g, '');
    }

    attachUploader.on('change', function (e) {
        sessionStorage.setItem("test", 1)
        var fd = new FormData()
        attachfile = attachUploader[0].files[0]

        var filesSize = attachfile.size
        // 禁止上传大于1m的文件
        console.log(attachfile.size)
        if (filesSize > maxSize) {
            $.alert("文件大于1M，不能上传")
            return
        }

        fd.append("upload", attachfile)
        $.ajax({
            url: "/api/v1/attach/upload",
            data: fd,
            type: "POST",
            contentType: false,
            processData: false,
            success: function (res) {
                //成功
                console.log(res)
                // return
                if (res.code == 200) {
                    // 并发下会 服务端 session 写入会有问题，由客户端控制改为串行
                    if (!jattachparent.find('.attachlist').length) {
                        jattachparent.append('<fieldset class="fieldset"><legend>上传的附件</legend><ul class="attachlist"><ul></fieldset>');
                    }

                    // 添加福建区域
                    message = res.data
                    addAttachLi(message.url, message.filetype, 1, message.orgfilename)

                    $.alert("上传成功")
                    /*setTimeout(function(){
                        location.reload()
                    }, 5000)*/
                } else {
                    $.alert(res.message)
                    return
                }
            }
        })
    });

    function addAttachLi(url, filetype, aid, orgfilename) {
        $('.attachlist').append('<li aid="' + aid + '"><a class="attachfile" orgfilename="' + orgfilename + '"  href="' + message.url + '" target="_blank"><i class="icon filetype ' + filetype + '"></i> ' + orgfilename + '</a> <a onclick="deleteAttach(this)" href="javascript:void(0);" class="delete ml-2"><i class="icon-remove"></i> 删除</a></li>');
    }

    function deleteAttach(elem) {
        if ($('.attachlist').find("li").length == 1) {
            $('.fieldset').remove()
        } else {
            $(elem).parent().remove()
        }
    }

    function randomChar(num) {
        var x = "0123456789qwertyuioplkjhgfdsazxcvbnm";
        var tmp = "";
        var timestamp = new Date().getTime();
        for (var i = 0; i < num; i++) {
            tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
        }
        return "newthread" + timestamp + tmp
    }

    $('form[method="POST"]').append('<input type="hidden" name="unique_token" value="' + "uid" + {{.sessions.Userid }} +randomChar(11) + '" />');

    // 标签相关
    function getTags(fid) {
        $.ajax({
            url: "/api/v1/forum/" + fid + "/tagcate",
            method: "GET",
            success: function (res) {
                console.log(res)
                tagdiv = ""
                if (res.code == 200) {
                    data = res.data
                    for (var tag of data) {
                        console.log(tag)
                        tagdiv += `<div>
                                <table>
                                    <tbody>
                                        <tr>
                                            <td valign="top" style="white-space: nowrap">
                                                <span class="grey">` + tag.TagCate.name + `：</span>
                                            </td>
                                            <td>`;
                        tags = tag.TagCate.Tags
                        for (var ltag of tags) {
                            tagdiv += `<a style="padding: 0 0.3rem" href="#" onclick="toggleclass(this)" rel="nofollow" tagid="` + ltag.id + `">` + ltag.name + `</a>`
                        }
                        tagdiv += `</td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>`
                    }
                }
                $("#taglist").html(tagdiv)
            }
        })
    }

    getTags(1)

    $("#select_forum_id").on("change", function () {
        console.log($(this).val())
        getTags($(this).val())
    })

    function toggleclass(ele) {
        $(ele).toggleClass("tagactive")
    }
</script>


{{ template "layout/footer" .}}

{{/*<div>
    <table>
        <tbody>
        <tr>
            <td valign="top" style="white-space: nowrap">
                <span class="grey">电影时间：</span>
            </td>
            <td>
                <a href="forum-index-fid-951-typeid1-0-typeid2-0-typeid3-0-typeid4-1238897.htm" rel="nofollow">2019</a>
                <a href="forum-index-fid-951-typeid1-0-typeid2-0-typeid3-0-typeid4-1238897.htm" rel="nofollow">2019</a>
            </td>
        </tr>
        </tbody>
    </table>
</div>*/}}
